package com.xxwy.avltree;

import com.sun.org.apache.bcel.internal.generic.NEW;
import com.xxwy.map.Map;

import java.util.ArrayList;

/**
 * @author xxwy
 * 二分搜索树 + avl树 所有的操作
 */
public class AVLTree<K extends Comparable, V> implements Map<K, V> {

    private class Node {
        private Node left;
        private Node right;
        private K key;
        private V value;
        private int height;

        public Node(K key, V value, Node left, Node right) {
            this.left = left;
            this.right = right;
            this.key = key;
            this.value = value;
            height = 1;
        }

        public Node(K key, V value) {
            this(key, value, null, null);
        }
    }

    private Node root;
    private int size;

    private int getHeight(Node node) {
        if (node == null) {
            return 0;
        }
        return node.height;
    }

    private int getBalanceFactor(Node node) {
        if (node == null) {
            return 0;
        }
        return getHeight(node.left) - getHeight(node.right);
    }

    @Override
    public void add(K key, V value) {
        root = add(root, key, value);

    }

    private Node add(Node node, K key, V value) {
        if (root == null) {
            size++;
            return new Node(key, value);
        }
        if (node.key.compareTo(key) < 0) {
            node.left = add(node.left, key, value);
        } else if (node.key.compareTo(key) > 0) {
            node.right = add(node.right, key, value);
        } else {
            node.value = value;
        }

        //更新height
        node.height = 1 + Math.max(getHeight(node.left), getHeight(node.right));
        int balanceFactor = getBalanceFactor(node);
        if(Math.abs(balanceFactor)>1) {
            node = balance(node,balanceFactor);
        }

        return node;
    }

    private Node balance(Node node, int balanceFactor) {
        //左子树的高度比右子树的高度大,直接右转
        if (balanceFactor > 1 && getBalanceFactor(node.left) >= 0) {
            return rightRotate(node);
        }
        //左子树的高度比右子树的高度小，直接左转
        if (balanceFactor < -1 && getBalanceFactor(node.right) <= 0) {
            return leftRotata(node);
        }

        //LR
        if (balanceFactor > 1 && getBalanceFactor(node.left) < 0) {
            node.left = leftRotata(node.left);
            return rightRotate(node);
        }
        //RL
        if (balanceFactor < -1 && getBalanceFactor(node.right) > 0) {
            node.right = rightRotate(node.right);
            return leftRotata(node);
        }
        return node;
    }

    private Node leftRotata(Node y) {
        Node x = y.right;
        Node T3 = x.left;
        x.left = y;
        y.right = T3;
        //更新height
        y.height = Math.max(getHeight(y.left), getHeight(y.right)) + 1;
        x.height = Math.max(getHeight(x.left), getHeight(x.right)) + 1;
        return x;
    }

    /**
     * 对节点y进行有旋转操作，返回旋转后新的根节点x
     * y                       x
     * / \                    /   \
     * x  T4      右旋转y      z     y
     * / \          ----->    / \   / \
     * z  T3                  T1 T2 T3 T4
     * / \
     * T1 T2
     *
     * @param y
     * @return
     */
    private Node rightRotate(Node y) {
        Node x = y.left;
        Node T3 = x.right;
        x.right = y;
        y.left = T3;

        //更新height
        y.height = Math.max(getHeight(y.left), getHeight(y.right)) + 1;
        x.height = Math.max(getHeight(x.left), getHeight(x.right)) + 1;
        return x;
    }




    /**
     * 返回key的Node
     *
     * @param node
     * @param key
     * @return
     */
    private Node getNode(Node node, K key) {
        if (node == null) {
            return null;
        }
        if (node.key.compareTo(key) < 0) {
            return getNode(node.left, key);
        } else if (node.key.compareTo(key) > 0) {
            return getNode(node.right, key);
        } else { //same
            return node;
        }
    }


    @Override
    public boolean contains(K key) {
        return getNode(root, key) != null;
    }

    @Override
    public V get(K key) {
        Node node = getNode(root, key);
        if (node != null) {
            return node.value;
        }
        return null;
    }

    @Override
    public void set(K key, V value) {
        Node node = getNode(root, key);
        if (node != null) {
            node.value = value;
        } else {
            throw new IllegalArgumentException(key + " doesn't exist");
        }
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public V remove(K key) {
        Node node = getNode(root, key);
        if (node != null) {
            root = remove(root, key);
            return root.value;
        }
        return null;
    }

    private Node remove(Node node, K key) {
        if (node == null) {
            return null;
        }
        Node retNode ;
        if (node.key.compareTo(key) < 0) {
            node.left = remove(node.left, key);
            retNode =  node;
        } else if (node.key.compareTo(key) > 0) {
            node.right = remove(node.right, key);
            retNode =  node;
        } else {  //当前node
            if (node.left == null) {
                Node rightNode = node.right;
                node.right = null;
                size--;
                retNode =  rightNode;
            }
            else if (node.right == null) {
                Node leftNode = node.left;
                size--;
                node.left = null;
                retNode =  leftNode;
            }
            //左右子树都不为null
            //找到比代删除接待大的最小节点，即代删除节点子树的最小节点
            //用这个节点代删除节点
            else {
                Node successor = minmum(node.right);
                successor.right = removeMin(node.right);
                successor.left = node.left;
                node.left = node.right = null;
                retNode = successor;
            }
        }
        if(retNode == null){
            return null;
        }
        retNode.height = 1 + Math.max(getHeight(retNode.left), getHeight(retNode.right));
        int balanceFactor = getBalanceFactor(retNode);
        if(Math.abs(balanceFactor)>1) {
            retNode = balance(retNode,balanceFactor);
        }
        return retNode;
    }

    private Node removeMin(Node node) {
        if (node.left == null) {
            node.right = null;
            size--;
            return node.right;
        }
        return removeMin(node.left);

    }

    private Node minmum(Node node) {
        if (node.left == null) {
            return node;
        }
        return minmum(node.left);
    }

    public boolean isBalanced() {
        return isBalanced(root);
    }

    private boolean isBalanced(Node node) {
        if (node == null) {
            return true;
        }
        int balanceFactor = getBalanceFactor(node);
        if (Math.abs(balanceFactor) > 1) {
            return false;
        }
        return isBalanced(node.left) && isBalanced(node.right);

    }


    public boolean isBST() {
        ArrayList<K> ks = new ArrayList<>();
        inOrder(root, ks);
        for (int i = 0; i < ks.size(); i++) {
            if (ks.get(i - 1).compareTo(ks.get(i)) > 0) {
                return false;
            }
        }
        return true;
    }

    private void inOrder(Node node, ArrayList<K> ks) {
        if (node == null) {
            return;
        }
        inOrder(node.left, ks);
        ks.add(node.key);
        inOrder(node.right, ks);
    }
}
